import React from 'react'
import { info, success, Checkbox, Modal, Table, Button, IconFont, Link, TitleBar } from '../../ui-components'
import { connect } from 'react-redux'
import style from './style.myTeam'
import cx from 'classnames'
import util from '../../util'
import moment from 'moment'
import userStatus from '../../constants/userStatus'
import { map as tableMap } from '../../ui-components/table'
import { u } from '../../actions/util'

const ROOT_TEAM = '2b1e6d025ac28868'

moment.locale('zh-cn')

export default
@connect(({team,app, user}) => ({ team,app, user }))
class MyTeam extends React.Component {

  state = {
    isFetchingTeamUsers: false,
    isFetchingTeamAncestorChildren: false,
    configAuth: false,
    roles: []
  }

  pageSize = 30
  pageNumber = 1

  handleSearch(e) {
    const { value } = e.target
    const { teamId } = this.props.location.query

    util.throttle(() => {
      if (this.props.manage) {
        this.props.router.push(`/hr/index?${util.body({teamId, keyword: value})}`)
      } else {
        this.props.router.push(`/team/myTeam/?${util.body({teamId, keyword: value})}`)
      }
    })
  }

  componentWillReceiveProps(props) {
    const { teamId, keyword } = props.location.query
    const { teamId:prevTeamId, keyword: prevKeyword } = this.props.location.query

    // 切换team
    if (teamId != prevTeamId) {
      this.fetchNavs(teamId)
      this.fetchTeamUsers(props)
    }

    // 切换关键字
    if (keyword != prevKeyword) {
      this.fetchTeamUsers(props)
    }

    if (props.team.isFetchingTeamUsers !== this.props.team.isFetchingTeamUsers) {
      this.setState({
        isFetchingTeamUsers: false
      })
    }

    if (props.team.isFetchingTeamAncestorChildren !== this.props.team.isFetchingTeamAncestorChildren) {
      this.setState({
        isFetchingTeamAncestorChildren: false
      })
    }

    if (props.user.roles.length && !this.props.user.roles.length) {
      this.setState({
        roles: props.user.roles
      })
    }
  }

  componentDidMount() {

    this.setState({
      isFetchingTeamUsers: true,
      isFetchingTeamAncestorChildren: true
    })

    const { teamId } = this.props.location.query

    this.fetchNavs(teamId)
    this.fetchTeamUsers()
  }

  fetchNavs(teamId) {
    this.props.fetchTeamAncestorChildren(teamId || ROOT_TEAM)
  }

  fetchTeamUsers(props) {
    props = props || this.props
    let { teamId, keyword, pageNumber } = props.location.query

    if (!teamId) {
      teamId = ROOT_TEAM
    }
    if (pageNumber == null) pageNumber = this.pageNumber

    this.props.fetchTeamUsers({
      teamId,
      keyword,
      pageNumber,
      pageSize: this.pageSize
    })
  }

  renderAncestorTeams(list) {
    if (util.isNull(list)) return null
    list = util.deepClone(list)

    for(var i=0;i<list.length;i++) {
      for(var j=0;j<list.length;j++) {
        if (list[i].parentTeamId == list[j].teamId) {
          list[j].children = [list[i]]
        }
      }
    }

    list = list.filter(item => {
      return util.isEqual(item.parentTeamId, ROOT_TEAM)
    })

    function render(list) {
      if (util.isNull(list) || this.state.isFetchingTeamAncestorChildren) return null
      return (
        <ul>
        {
          list.map((team, i) => (
            <li key={i}>
              <Link 
                noHover={!team.children}
                className={cx({
                  [style.currentTeam]: !team.children
                })}
                to={team.children? (this.props.manage? (`#/hr/index?teamId=${team.teamId}`): (`#/team/myTeam?teamId=${team.teamId}`)) : null}
              >
                <span>{ team.teamName }</span>
              </Link>
              {
                team.children?
                <IconFont size="12" rotate="-90" value="arrow"/>: null
              }
              {
                render.call(this, team.children)
              }
            </li>
          ))
        }
        </ul>
      )
    }

    return (
      <ul className={style.ancestorTeams}>
        {
          render.call(this, list)
        }
      </ul>
    )
  }


  renderChildrenTeams(list) {
    if (!list.length || this.state.isFetchingTeamAncestorChildren) return null
    return (
      <div className={style.childrenTeams}>
        <p>子团队:</p>
        <ul>
          {
            list.map((team, i) => (
              <li key={i}>
                <Link 
                  className={cx({
                    [style.currentTeam]: team.teamId == this.props.location.query.subTeamId
                  })}
                  to={team.teamId == this.props.location.query.subTeamId? null: `#/team/myTeam?teamId=${team.teamId}`} 
                  to={team.teamId == this.props.location.query.subTeamId? null: (this.props.manage? `#/hr/index?teamId=${team.teamId}`: `#/team/myTeam?teamId=${team.teamId}`)} 
                  label={ team.teamName }/>
              </li>
            ))
          }
        </ul>
      </div>
    )
  }

  handlePageChage(_pageNumber) {
    const { pageNumber, ...others } = this.props.location.query

    this.props.router.push(this.props.manage? `hr/index?pageNumber=${_pageNumber}&${util.body(others)}`: `/team/myteam?pageNumber=${_pageNumber}&${util.body(others)}`)
  }

  renderTeamUsers() {
    //权限控制根据roleList 配置
    let managable = 0;
    if(this.props.app){
      const {roleNameList = []} = this.props.app.profile || {}; 
      if(~roleNameList.indexOf('HR')) {
        managable = 1;
      }else if(~roleNameList.indexOf('orgAdmin')) {
        managable = 2;
      }
    }
    const { totalRecordNum, UserProfiles: list } = this.props.team.teamUser
    const config = {
      pagin: typeof totalRecordNum === 'number' && {
        pageSize: this.pageSize,
        pageNumber: this.props.location.query.pageNumber || this.pageNumber,
        totalNumber: totalRecordNum,
        onChange: ::this.handlePageChage,
        fetch: ::this.fetchTeamUsers
      },
      model: {
        fullName: '姓名',
        userEmploymentVO: '状态',
        jobTitleName: '职位',
        enrollDate: '入职时间',
        others: ''
      },
      config: {
        others: '.5',
      },
      map: {
        fullName: this.props.manage? (v, user) => tableMap.fullName.call(null, v, user, '_self'): tableMap.fullName,
        userEmploymentVO: value => {
          return <span className={cx({
            [style.userStatus]: true,
            [style.leave]: value == 4
          })}
          >{ userStatus(value) || ''}</span>
        },
        enrollDate: value => value && moment(value).format('YYYY.MM.DD'),
        others: (value, item) => {
          if (this.props.manage && !util.isEqual(u.userId, item.userId)) return (
            <span data-role="table-hover">
              <Link
                label="管理"
                to={`#/hr/team-memeber-edit/${item.userId}`} className={style['config-auth']}/>
            </span>
          );
          /*
          if (managable && !util.isEqual(u.userId, item.userId)) return (
            <span data-role="table-hover">
              <Link onClick={() => this.requestConfigAuth(item)} className={style['config-auth']} label='配置权限'/>
            </span>
          )*/
          return null
        } 
      }
    }

    let evts = {}
    if (this.props.manage) {
      evts = {
        onTrClick: index => this.props.router.push(`/hr/team-memeber-edit/${list[index].userId}`)
      }
    }

    return (
      <Table
        {...evts}
        loading={this.state.isFetchingTeamUsers}
        className={cx(style.teamUsers, { [style.hr]: this.props.manage })}
        data={list}
        { ...config }
      />
    )
  }

  toggleRoles(id) {
    this.setState({
      roles: this.state.roles.map((r, i) => {
        if(r.roleId == id) {
          return {
            ...r,
            flag: !r.flag
          }
        }
        return r
      })
    })
  }

  updateAuth() {
    info('更新中...')
    const { configAuthUser, roles } = this.state;
    this.props.updateUserRole(roles.filter(r => r.flag).map(r => ({ idValue: r.roleId })), configAuthUser.userId, () => {
      success('更新成功!')
    })
    this.cancelConfigAuth()
  }

  requestConfigAuth(user) {
    this.props.fetchRole(user.userId)
    this.setState({
      configAuthUser: user,
      configAuth: true,
      roles: []
    })
  }

  cancelConfigAuth() {
    this.setState({
      configAuth: false,
      configAuthUser: null
    })
    this.props.resetUser()
  }

  render() {
    const { ancestorTeams=[], childrenTeams=[] } = this.props.team.teamAncestorChildren
    return (
      <div>
        <TitleBar label={this.props.manage? '员工花名册': '团队'}/>
        <div>
          {
            this.renderAncestorTeams(ancestorTeams)
          }
          {
            this.renderChildrenTeams(childrenTeams)
          }
          <div className={style.search}>
            <div className={style.input}>
              <input 
                onChange={::this.handleSearch}
                placeholder="输入姓名/姓名拼音..."/>
            </div>
          </div>
          {
            this.renderTeamUsers()
          }
        </div>
        <Modal
          active={this.state.configAuth}
          onRequestClose={::this.cancelConfigAuth}
          actions={[
            'cancel',
            ::this.updateAuth
          ]}
          title={`给${(this.state.configAuthUser || {}).fullName || ''}配置权限`}
        >
          <div className={style['auth-check-list']}>
            {
              this.state.roles.map((v, i) => (
                <Checkbox 
                  className={style['auth-check']}
                  disabled={!v.editable}
                  active={v.flag}
                  onClick={() => {
                    if (v.editable) {
                      this.toggleRoles(v.roleId)
                    }
                  }}
                  key={i}
                  label={v.roleDesc}
                />
              ))
            }
          </div>
        </Modal>
      </div>
    )
  }
}
